package com.epam.utils;

import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.epam.utils.JsfUtil;

public class Login {

	private String login;
	private String pass;
	private String message;

	private Logger logger = Logger.getLogger(Login.class);

	public String getLogin() {
		return login;
	}

	public void setLogin(String login) {
		this.login = login;
	}

	public String getPass() {
		return pass;
	}

	public void setPass(String pass) {
		this.pass = pass;
	}

	public String getMessage() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		message = (String) facesContext.getExternalContext()
				.getRequestParameterMap().get("message");
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String tryLogin() {

		HttpServletRequest request = JsfUtil.getRequest();

		try {
			request.login(login, pass);
		} catch (ServletException e) {
			logger.error(e.toString());
			JsfUtil.addMessage("reg_login_form:login",
					"Wrong login or password");
			return "fail";
		}

		System.out.println("isUserInRole CLIENT" + request.isUserInRole("CLIENT"));
		System.out.println("isUserInRole MANAGER" + request.isUserInRole("MANAGER"));
		System.out.println("request.getRemoteUser() = "
				+ request.getRemoteUser());
		System.out.println("request.getUserPrincipal() = "
				+ request.getUserPrincipal());
		System.out.println("request.getAuthType()" + request.getAuthType());

		if (request.isUserInRole("MANAGER")) {
			return "manager";
		} else if (request.isUserInRole("CLIENT")) {
			return "client";
		}
		return null;
	}

}
